package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> findAll() {
        //调用方法
        List<Category> categoryList = categoryMapper.findAll();
        return categoryList;
    }

    @Override
    public void save(Category category) {
        //补全信息
        //雪花算法得到唯一id
        category.setId(IdUtil.getSnowflake(1,1).nextId());
//        //补全创建 修改时间
//        category.setCreateTime(new Date());
//        category.setUpdateTime(new Date());
//        //创建  修改用户
//        category.setCreateUser(1L);
//        category.setUpdateUser(1L);

        //调用方法
        categoryMapper.save(category);
    }

    @Override
    public void update(Category category) {
//        //修改时间
//        category.setUpdateTime(new Date());
//        //修改用户
//        category.setUpdateUser(1L);//先写死
        //调用方法
        categoryMapper.updateById(category);
    }

    @Override
    public ResultInfo delete(Long id) {
        //查询是否有菜品
        Integer countDish = categoryMapper.findByDish(id);
        if (countDish > 0) {
            throw new CustomException("当前分类下存在菜品，不能删除");
        }
        //套餐查询
        Integer countSetmeal = categoryMapper.findBySetmeal(id);
        if (countSetmeal > 0) {
//            return ResultInfo.error("当前分类下存在套餐，不能删除");
            throw new CustomException("当前分类下存在套餐，不能删除");
        }
        //否则就删除
        categoryMapper.delete(id);
        return ResultInfo.success(null);
    }

    @Override
    public List<Category> findList(Integer type) {
        //添加条件
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(Category::getType, type);
        //利用条件查询
        List<Category> categoryList = categoryMapper.selectList(categoryLambdaQueryWrapper);
        //返回
        return categoryList;
    }


}
